// OrderPaidConsumer.java
package edu.del.springbootredisbusinesspractice.consumer;

import edu.del.springbootredisbusinesspractice.commons.config.RabbitMQConfig;
import edu.del.springbootredisbusinesspractice.mapper.OrdersMapper;
import edu.del.springbootredisbusinesspractice.pojo.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import com.rabbitmq.client.Channel;

import java.io.IOException;

@Slf4j
@Service
public class OrderPaidConsumer {

    @Autowired
    private OrdersMapper ordersMapper;

    @RabbitListener(
            queues = RabbitMQConfig.ORDER_PAID_QUEUE,
            containerFactory = "jsonRabbitListenerContainerFactory"
    )
    public void handlePaidOrder(
            @Payload Orders order,
            Channel channel,
            @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            if (order == null) {
                log.error("【支付成功消费】订单为空, deliveryTag: {}", deliveryTag);
                channel.basicNack(deliveryTag, false, false);
                return;
            }

            log.info("【支付成功消费】开始处理订单支付成功逻辑，orderNo: {}", order.getOrderNo());

            // TODO: 这里添加实际业务，如发货、通知等

            log.info("【支付成功消费】订单后续处理完成，orderNo: {}", order.getOrderNo());

            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            log.error("【支付成功消费】处理异常，orderNo: {}", order.getOrderNo(), e);
            try {
                channel.basicNack(deliveryTag, false, false);
            } catch (IOException ex) {
                log.error("【支付成功消费】Nack失败", ex);
            }
        }
    }
}